package com.echo.code.thread;

import com.echo.code.thread.latch.Latch;
import com.echo.code.thread.latch.impl.CountDownLatch;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.junit.Test;

/**
 * Created by baiyap on 2018/7/20
 */
public class LatchTestCase extends Thread {

  private final Latch latch;

  public LatchTestCase(Latch latch) {
    this.latch = latch;
  }

  @Test
  public static void latchTestCase() throws InterruptedException, TimeoutException {
    // limit is 4
    Latch latch = new CountDownLatch(4);
    new LatchTestCase(latch).start();
    new LatchTestCase(latch).start();
    new LatchTestCase(latch).start();
    new LatchTestCase(latch).start();
    latch.await();
    System.out.println("over");
  }

  public static void main(String[] args) throws InterruptedException, TimeoutException {
    latchTestCase();
  }

  @Override
  public void run() {
    try {
      TimeUnit.SECONDS.sleep(ThreadLocalRandom.current().nextInt(10));
    } catch (InterruptedException e) {
      e.printStackTrace();
    } finally {
      latch.countDown();
    }
  }
}
